<?php

declare(strict_types=1);

namespace App\Controller;


use App\Model\DevicePortErrLog;
use App\Model\Order;
use Carbon\Carbon;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use Swoole\Server;
use Trait\ResponseMsg;
use App\Model\Normal;

class DeviceController extends AbstractController
{

    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);

    }

    public function start(RequestInterface $request){
        $data = $request->post();
        if(!$data['number']){
            Normal::logger('订单号不存在','order-start');
        }
        Normal::logger('订单开始处理'.json_encode($data),'order-start');
        $order = Order::query()->where('number',$data['number'])->first();
        try{
            if($data['result'] != 0){
                $order->fail($data['resultText']);
                Normal::logger('开启失败:'.json_encode($data),'order-start');
            }else{
                $order->start_at = Carbon::now();
                $order->status = Order::STATUS_USING;
                $order->save();
            }
            return $this->success();
        }catch (\Exception $e){
            return $this->error($e->getMessage().$e->getTraceAsString());
        }
    }

    public function end(RequestInterface $request){
        $data = $request->post();
        if(!$data['number']){
            Normal::logger('订单号不存在','order-start');
        }
        $cacheKey = 'order_end_lock_' . $data['number'];
        $lock = $this->redis->setnx($cacheKey, time());

        if (!$lock) {
            // 检查锁是否过期（超过1分钟）
            $lockTime = $this->redis->get($cacheKey);
            if ($lockTime && (time() - $lockTime) < 60) {
                Normal::logger($data['number'].'订单正在处理中，请稍后再试','order-end');
                return $this->error('订单正在处理中，请稍后再试');
            } else {
                // 锁过期，重新设置
                $this->redis->del($cacheKey);
                $this->redis->setnx($cacheKey, time());
            }
        }
        // 设置1分钟过期时间
        $this->redis->expire($cacheKey, 60);
        try{
            $order = Order::query()->where('number',$data['number'])
                ->with(['detail', 'charge', 'distributor', 'station', 'user'])
                ->first();
            if(!$order){
                Normal::logger($data['number'].'订单不存在','order-end');
                return $this->error('订单不存在');
            }
            if($order->status != Order::STATUS_USING){
                 Normal::logger($data['number'].'订单已结束退出再次结算'.json_encode($order),'order-end');
                 return $this->error('订单已结束');
            }
            if($order->detail && $order->detail->duration > 180){
                $order->stop($data);
            }else{
                $order->fail($data['stop_reason_text']);
            }
            Normal::logger('订单结束处理'.json_encode($data),'order-end');
            return $this->success();
        }catch (\Exception $e){
            Normal::logger('end-error'.$e->getMessage().$e->getTraceAsString(),'order-end');
            return $this->success();
        }
    }


    /**
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getWarningList(RequestInterface $request){
        $sn = $request->input('sn');
        $start = $request->input('start');
        $end = $request->input('end');
        $page = $request->input('page',1);
        $limit = $request->input('limit',10);
        $status = $request->input('status',0);
        $list = DevicePortErrLog::where(function ($query) use ($start,$end,$status,$sn) {
                if($start && $end){
                    $query->whereBetween('created_at',[$start,$end]);
                }
                if($status != ''){
                    $query->where('status',$status);
                }
                if($sn){
                    $query->whereHas('device', function($q) use ($sn) {
                        $q->where('sn', $sn);
                    });
                }
            })
            ->with('device')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get();
        return $this->success($list);
    }


}
